package com.zjitc.controller;

import com.zjitc.pojo.User;
import com.zjitc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public String showList(@RequestParam(defaultValue = "1")int page,
                           @RequestParam(defaultValue = "3")int pageSize,
                           Model model){
        int countPage =userService.pageCount();
        int totalPages = (int)Math.ceil((double)countPage/pageSize);

        if (page<1)page=1;
        if(page>totalPages && totalPages>0)page=totalPages;

        int offset = (page-1)*totalPages;

        List<User> users = userService.getUserPage(offset,pageSize);
        model.addAttribute("users",users);
        model.addAttribute("totalPages",totalPages);
        model.addAttribute("currentPage",page);
        return "userList";
    }

    @GetMapping("/search")
    public String search(@RequestParam(defaultValue = "1")int page,
                         @RequestParam(defaultValue = "3")int pageSize,
                         @RequestParam String keyword,
                         Model model){
        int pageCount = userService.countByKeyword(keyword);
        int totalPages = (int)Math.ceil((double)pageCount/pageSize);
        if (page<1)page=1;
        if(page>totalPages && totalPages>0)page=totalPages;

        int offset = (page-1)*totalPages;

        List<User> users =userService.search(keyword,offset,pageSize);

        model.addAttribute("users",users);
        model.addAttribute("totalPages",totalPages);
        model.addAttribute("currentPage",page);
        model.addAttribute("keyword",keyword);
        return "userList";
    }

    @GetMapping("/add")
    public String showAdd(){
        return "addUser";
    }

    @PostMapping("/add")
    public String addUser(User user){
        userService.addUser(user);
        return "redirect:/user/list";
    }

    @GetMapping("/delete/{id}")
    public String deleteUser(@PathVariable int id){
        userService.deleteUser(id);
        return "redirect:/user/list";
    }

    @PostMapping("/update")
    public String updateUser(User user){
        userService.updateUser(user);
        return "redirect:/user/list";
    }

    @GetMapping("/edit/{id}")
    public String editUser(@PathVariable int id,Model model){
        User user= userService.getUserId(id);
        model.addAttribute("user",user);
        return "editUser";
    }
}
